<template>
  <div style="height: 100%">
    <AHMF
      :asideWidth="300"
      :rightTitleShow="false"
      :AShow="false"
      :FShow="true"
    >
      <template #header>
        <topSearcher
          :searchOptions="searchOptions"
          @onQuery="onQuery"
          @onReset="onReset"
        ></topSearcher>
      </template>
      <template #main>
        <div
          style="margin-bottom: 10px; display: flex"
          v-loading="tableLoading"
        >
          <div class="item-container">
            <div v-for="n in tableData" :key="n.id" class="item-main">
              <div
                class="item"
                @click="
                  itemClick(n.templateNum == 0 ? 'addConfig' : 'editConfig', n)
                "
              >
                <div
                  class="status"
                  :style="{ background: n.isSystem == 1 ? 'red' : '#3c9cff' }"
                >
                  {{ n.isSystem == 1 ? "系统" : "个人" }}
                </div>
                <div @click.stop>
                  <el-dropdown trigger="click">
                    <el-button type="text">
                      <i style="font-size: 20px" class="el-icon-more"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        @click.native.stop="itemClick('viewConfig', n)"
                        >详情</el-dropdown-item
                      >
                      <el-dropdown-item
                        @click.native.stop="add_edit_fn('edit', n)"
                        >编辑</el-dropdown-item
                      >
                      <el-dropdown-item @click.native.stop="tempConfigFn(n)"
                        >场景配置</el-dropdown-item
                      >

                      <el-dropdown-item @click.native.stop="delFn(n)"
                        >删除</el-dropdown-item
                      >
                      <el-dropdown-item
                        @click.native.stop="itemClick('copy', n)"
                        >复制</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>

                <div class="field" data-label="场景编码:">
                  {{ n.sceneCode }}
                </div>
                <div class="field" data-label="模板个数:">
                  <span style="color: red">{{ n.ediotrNum || 0 }}</span>
                  <span style="margin-left: 10px">|</span>
                  <span style="margin-left: 10px; color: #3c9cff">{{
                    n.templateNum || 0
                  }}</span>
                  个
                </div>
                <div class="field" data-label="创建时间:">{{ n.crTime }}</div>
              </div>
              <div style="font-weight: bold">{{ n.sceneName }}</div>
            </div>
            <div class="item-main">
              <div class="item additem" @click.stop="add_edit_fn('add')">
                <i style="font-size: 40px" class="el-icon-plus"></i>
              </div>
              <div style="font-weight: bold; color: #3c9cff">添加场景</div>
            </div>
            <Edialog
              :outershow="addDialogShow"
              :title="title"
              width="50%"
              @saveFn="saveFn"
              @close="closeFn"
              :saveClick="true"
            >
              <el-form
                ref="addForm"
                :model="addForm"
                label-width="80px"
                :rules="addFormRules"
              >
                <el-form-item label="场景编码" prop="sceneCode">
                  <el-input
                    :disabled="title == '编辑'"
                    v-model="addForm.sceneCode"
                    autocomplete="off"
                  ></el-input>
                  <!-- <div v-else style="text-align: left">
                    {{ addForm.sceneCode }}
                  </div> -->
                </el-form-item>
                <el-form-item label="场景名称" prop="sceneName">
                  <el-input
                    v-model="addForm.sceneName"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="场景备注" prop="remark">
                  <el-input
                    v-model="addForm.remark"
                    autocomplete="off"
                    type="textarea"
                  ></el-input>
                </el-form-item>
              </el-form>
            </Edialog>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="flex">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageInfo.currPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
          >
          </el-pagination>
        </div>
      </template>
    </AHMF>
    <!-- 模板配置 -->
    <template_config
      ref="template_config"
      @refresh="getTableData"
    ></template_config>
    <!-- 模板编辑 -->
    <template_edit ref="template_edit"></template_edit>
  </div>
</template>
<script>
import topSearcher from "@/components/topSearcher/topSearcher.vue";
import AHMF from "@/components/topSearcher/AHMF.vue";
import ETable from "@/components/ETable";
import Edialog from "@/components/Edialog";
import template_config from "./components/template_config.vue";
import template_edit from "./components/template_edit.vue";

import {
  putSceneInfoApi,
  postSceneInfoApi,
  deleteSceneInfoByIds,
  SceneInfoApi,
  SceneInfoByIdApi,
  SceneInfoCopyByIdApi,
  putSceneTemplateApi,
  postSceneTemplateApi,
  SceneTemplateCopyByIdApi,
  deleteSceneTemplateByIds,
  SceneTemplateApi,
  SceneTemplateByIdApi,
} from "@/api/sceneManage";
export default {
  components: {
    ETable,
    Edialog,
    AHMF,
    topSearcher,
    template_config,
    template_edit,
  },

  data() {
    return {
      title: "新增",
      addFormRules: {
        sceneCode: [
          { required: true, message: "请输入场景编码", trigger: "blur" },
        ],
        sceneName: [
          { required: true, message: "请输入场景名称", trigger: "blur" },
        ],
      },
      addForm: {
        sceneCode: "",
        sceneName: "",
        remark: "",
      },
      // 新增弹窗
      addDialogShow: false,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 搜索字段
      searchOptions: [
        {
          type: "input",
          label: "场景名称",
          key: "sceneName",
          value: "",
        },
      ],
      tableHeight: "随便设置的字符串，只要是字符串，表格高度就会受控于外部样式",
      searchForm: {},
      tableData: [],
      tableLoading: false,
      pageInfo: {
        currPage: 1,
        pageSize: 10,
        total: 0,
      },
      batchData: [],
      batchDataIds: [],
      spreadsheetData: [],
      loading: false,
    };
  },
  mounted() {
    // this.getTableData();
  },
  methods: {
    add_edit_fn(type, data) {
      this.addDialogShow = true;
      this.title = type == "add" ? "新增" : "编辑";
      if (type == "edit") {
        this.$nextTick(() => {
          console.log(data);

          this.addForm = { ...data };
        });
      }
    },
    itemClick(type, data) {
      console.log("data", data);

      if (type == "addConfig") {
        this.tempConfigFn(data);
      } else if (type == "editConfig" || type == "viewConfig") {
        this.$refs.template_edit.openFn(type, data);
      } else if (type == "copy") {
        this.copyFn(data);
      }
    },
    copyFn(data) {
      this.$confirm(
        `确定要复制【${data.sceneCode}】${data.sceneName}的场景？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        if (data.id) {
          SceneInfoCopyByIdApi(data.id).then((res) => {
            if (res.data && res.data.bcode == 0) {
              this.$message.success("复制成功");
              this.getTableData();
            }
          });
        } else {
          this.$message.warning("复制失败");
        }
      });
    },
    //模板配置
    tempConfigFn(data) {
      this.$refs.template_config.manufacturerOpen(data);
    },
    saveFn() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (this.addForm.id) {
            postSceneInfoApi(this.addForm).then((res) => {
              if (res.data && res.data.bcode == 0) {
                this.$message.success("保存成功");
                this.addDialogShow = false;
                this.getTableData();
              }
            });
          } else {
            putSceneInfoApi(this.addForm).then((res) => {
              if (res.data && res.data.bcode == 0) {
                this.$message.success("保存成功");
                this.addDialogShow = false;
                this.getTableData();
              }
            });
          }
        }
      });
    },
    closeFn() {
      this.$refs.addForm.resetFields();
      this.addDialogShow = false;
    },
    async delFn(scope) {
      let t = await this.$confirm("确认删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      if (t) {
        let res = await deleteSceneInfoByIds(scope.id);
        if (res.data && res.data.bcode == 0) {
          // 页数大于一页并且当前页只有一条数据，删除后页数-1
          if (
            this.pageInfo.total % this.pageInfo.pageSize === 1 &&
            this.pageInfo.currPage > 1
          ) {
            this.pageInfo.currPage -= 1;
          }
          this.$message.success(res.data.bmsg || "删除成功");
          this.getTableData();
        }
      }
    },
    batchFn(data) {
      this.batchData = data;
      this.batchDataIds = data.map((item) => item.id);
    },
    async sortFun(obj) {
      console.log("---", obj);
      this.pageInfo.sortList = obj;
      if (obj == "") {
        return this.getTableData();
      }
      this.sortReq();
    },
    async sortReq() {
      console.log("this.searchForm", this.searchForm);

      this.loading = true;
      let res = await getSysSystemParamSort({
        currPage: this.pageInfo.currPage,
        pageSize: this.pageInfo.pageSize,
        sortList: this.pageInfo.sortList,
        ...this.searchForm,
      });
      this.tableData = res.data.bdata.gdata;
      this.pageInfo.total = res.data.bdata.total;
      this.loading = false;
    },
    // 获取表格数据
    async getTableData() {
      this.tableLoading = true;
      // 没有排序条件
      let obj = {
        currPage: this.pageInfo.currPage,
        pageSize: this.pageInfo.pageSize,
        ...this.searchForm,
      };
      if (obj.sortStr == "") {
        delete obj.sortStr;
      } else {
        // 有排序条件
        obj.sortStr = this.searchForm.sortStr;
      }

      let res = await SceneInfoApi(obj);
      if (res.data && res.data.bdata.total > 0) {
        this.tableData = res.data.bdata.gdata;
        this.pageInfo.total = res.data.bdata.total;
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.tableLoading = false;
    },
    onReset(searchForm) {
      console.log("重置", searchForm);
      // this.searchForm = searchForm;
      this.pageInfo.currPage = 1;
      this.onQuery(searchForm);
    },
    onQuery(searchForm) {
      console.log("查询", searchForm);
      this.searchForm = searchForm;
      this.getTableData();
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageInfo.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageInfo.currPage = val;
      this.getTableData();
    },
    onSubmit() {
      console.log("submit!");
    },
    handleNodeClick(data) {
      console.log(data);
      // this.spreadsheetData = JSON.parse(localStorage.getItem("loadData"));
    },
    handleClick(row) {
      console.log(row);
    },
    //树节点筛选
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
  },
};
</script>
<style lang="scss" scoped>
.item-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
  justify-content: flex-start;
}
.item {
  width: 100%; /* 一行5个，考虑到margin和padding，这里设置为18% */
  height: 120px;
  border: 1px solid #ccc;
  margin: 10px;
  padding: 10px 10px 10px 10px;
  position: relative;
  text-align: left; /* 使文字左对齐 */
  border-radius: 8px; /* 添加弧度 */
  display: flex;
  flex-direction: column;
  cursor: pointer;
}
.item-main {
  margin-bottom: 8px;
  width: 18%; /* 一行5个，考虑到margin和padding，这里设置为18% */
  margin-right: 30px;
}
.status {
  position: absolute;
  top: -25px; /* 调整位置，使其出格 */
  left: -15px; /* 调整位置，使其出格 */
  background-color: #007bff;
  color: white;
  font-size: 14px;
  padding: 3px 6px;
  border-radius: 5px; /* 添加圆角 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); /* 添加阴影 */
  transform: rotate(-45deg); /* 逆时针旋转45度 */
  transform-origin: bottom right; /* 设置旋转的基点 */
}
.el-dropdown {
  position: absolute;
  top: 0px;
  right: 10px;
  height: 30px;
}
.dropdown-button {
  position: absolute;
  top: 10px;
  right: 10px;
  color: #333;
}
.field {
  margin: 8px 0;
}
.field::before {
  content: attr(data-label);
  font-weight: bold; /* 加粗字体 */
  margin-right: 10px; /* 添加右边距 */
}
.additem {
  justify-content: center;
  align-items: center;
}
</style>
